package com.vitabuybuy.tv.ui.home.bidd

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityBiddingCommodityBinding
import com.vitabuybuy.tv.dialog.BiddingPopup
import com.vitabuybuy.tv.dialog.SharePopup
import com.vitabuybuy.tv.dto.BannerDto
import com.library.common.toast.XToast
import com.library.common.util.DateUtil
import com.library.common.util.MMKVContancts
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.ui.WebViewActivity
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.cart.ConfirmOrderActivity
import com.vitabuybuy.tv.ui.cart.OrderPayActivity
import com.vitabuybuy.tv.ui.home.bidd.viewmodel.BiddingZoneViewModel
import com.vitabuybuy.tv.ui.shopcenter.GoodsDetailsActivity
import com.vitabuybuy.tv.ui.shopcenter.store.StoreHomeActivity
import com.vitabuybuy.tv.ui.tencent.chat.ChatActivity
import com.vitabuybuy.tv.utils.WebViewUtils
import kotlinx.android.synthetic.main.activity_bidding_commodity.*

class BiddingCommodityActivity :
    BaseActivity<BiddingZoneViewModel, ActivityBiddingCommodityBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.activity_bidding_commodity

    private var scrollY = 0
    private val bannerlist = ArrayList<BannerDto.SlideListBean>()
    private var goodId: Int? = 0
    private var biddingId: Int? = 0
    private lateinit var hasFavDrawable: Drawable
    private lateinit var noneFavDrawable: Drawable
    private lateinit var remindDrawable: Drawable

    private var timer: CountDownTimer? = null

    override fun onGetBundle(bundle: Bundle?) {
        biddingId = bundle?.getInt("biddingId")
        goodId = bundle?.getInt("goodId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mViewModel = viewModel
        initBanner()
        WebViewUtils.defaultSetting(rcvCommodityDetail)
        hasFavDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_shoucang)!!
        hasFavDrawable.setBounds(
            0,
            0,
            hasFavDrawable.minimumWidth,
            hasFavDrawable.minimumHeight
        )
        noneFavDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_shoucang_n)!!
        noneFavDrawable.setBounds(
            0,
            0,
            noneFavDrawable.minimumWidth,
            noneFavDrawable.minimumHeight
        )
        remindDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_naozhog)!!
        remindDrawable.setBounds(
            0,
            0,
            remindDrawable.minimumWidth,
            remindDrawable.minimumHeight
        )
    }

    override fun observeData() {
        viewModel.getGoodsDetail(biddingId)
        viewModel.getGoodsList(goodId)
        viewModel.goodDetailDto.observe(this, Observer {
            for (str in it.product.images.split(";")) {
                val bannerDto = BannerDto.SlideListBean()
                bannerDto.image = str
                bannerlist.add(bannerDto)
            }
            my_banner.setBannerData(bannerlist)
            rcvCommodityDetail.loadDataWithBaseURL(
                null,
                WebViewUtils.htmlContent(it.product.description),
                "text/html",
                "UTF-8",
                null
            )
            if (it.status == getString(R.string.wait_start)) {
                btnPartIn.text = getString(R.string.make_an_appointment)
                tvGroupDeadline.apply {
                    text =
                        getString(R.string.soon_bidding) + it.startTime
                }
                llStar.apply {
                    setCompoundDrawables(null, remindDrawable, null, null)
                    text = if (it.isRemind) {
                        context.getString(R.string.already_remind)
                    } else {
                        context.getString(R.string.remind)
                    }
                }
            } else {
                btnPartIn.text = getString(R.string.part_in_now)
                llStar.text = getString(R.string.star)
                if (it.product.isFavorites) {
                    llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
                } else {
                    llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
                }
                if (it.remainingTime == 0L) {
                    tvGroupDeadline.apply {
                        setBackgroundColor(
                            ContextCompat.getColor(
                                mContext,
                                R.color.text_e0e0e0
                            )
                        )
                        text = getString(R.string.has_over)
                    }
                    btnPartIn.visibility = View.GONE
                } else {
                    startRemind(it.remainingTime)
                    btnPartIn.visibility = View.VISIBLE
                }
            }
            viewModel.getBidderList(biddingId, 1, 3)
        })
        viewModel.addressList.observe(this, Observer
        {
            viewModel.goodDetailDto.value?.run {
                BiddingPopup(this@BiddingCommodityActivity, this.securityDeposit, it, { bean ->
                    OrderPayActivity.openActivity(
                        mContext,
                        this.securityDeposit,
                        this.id,
                        bean.id,
                        OrderPayActivity.FROM_BIDDING
                    )
                }, {
                    WebViewActivity.openActivity(mContext, "", "", 13)
                }).showPopupWindow()
            }
        })
    }

    private fun startRemind(remainingTime: Long) {
        timer = object : CountDownTimer(remainingTime * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                tvGroupDeadline.apply {
                    setBackgroundResource(R.drawable.rect_0_all_pink_red)
                    text = String.format(
                        getString(R.string.on_going),
                        DateUtil.formatSeconds(millisUntilFinished / 1000)
                    )
                }
            }

            override fun onFinish() {
            }
        }
        timer!!.start()
    }


    override fun onDestroy() {
        super.onDestroy()
        if (timer != null)
            timer?.cancel()
    }


    override fun eventHandling() {
        setOnclickNoRepeat(iv_finish, btn_share, rlBidRecord, btntvAlonePrice, btnPartIn, llStar,llCustomerService){v->
            when (v) {
                iv_finish -> finish()
                btn_share -> {
                    SharePopup(this).showPopupWindow()
                }
                rlBidRecord -> {
                    BiddingRecordActivity.openActivity(mContext, biddingId)
                }
                btntvAlonePrice -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    ConfirmOrderActivity.openActivity(
                        mContext,
                        viewModel.goodDetailDto.value!!.goods.id,
                        1,
                        ConfirmOrderActivity.BUY_NOW
                    )
                }
                btnPartIn -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    if (viewModel.goodDetailDto.value!!.status == getString(R.string.wait_start)) {
                        if (viewModel.goodDetailDto.value!!.isBought) {
                            XToast.normal(getString(R.string.yor_are_already_apply_pls_wait_open))
                        } else {
                            viewModel.getAddressList()
                        }
                    } else {
                        if (viewModel.goodDetailDto.value!!.isBought) {
                            BiddingActivity.openActivity(mContext, biddingId)
                        } else {
                            viewModel.getAddressList()
                        }
                    }
                }
                llStar -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    viewModel.goodDetailDto.value?.run {
                        if (this.status == getString(R.string.underway)) {
                            viewModel.collectOrcancel(
                                this.product.id,
                                this.product.isFavorites
                            )
                        } else {
                            viewModel.remindOrCancelBidding(
                                this.id,
                                this.isRemind
                            )
                        }
                    }
                }
                llCustomerService->{
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    viewModel.goodDetailDto.value?.run {
                        val chatInfo = ChatInfo()
                        chatInfo.type = TIMConversationType.C2C
                        chatInfo.id = this.store.id.toString()
                        chatInfo.chatName = this.store.name
                        ChatActivity.openActivity(mContext, chatInfo)
                    }
                }
            }
        }
        scrollview.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
            this.scrollY = scrollY
            if (scrollY <= 0) {
                rl_title.setBackgroundColor(Color.argb(0, 255, 255, 255))
            } else {
                val scale = scrollY.toFloat() / rl_title!!.height
                val alpha = 255 * if (scale > 1) 1f else scale
                rl_title.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
            }
        })
        onClick({
            StoreHomeActivity.openActivity(
                mContext,
                viewModel.goodDetailDto.value?.store?.id,
                viewModel.goodDetailDto.value?.store?.name
            )
        }, btnEnterShop, llShop)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 1001) {
            viewModel.goodDetailDto.value!!.isBought = true
            if (viewModel.goodDetailDto.value!!.status == getString(R.string.wait_start)) {
                XToast.normal(getString(R.string.yor_are_already_apply_pls_wait_open))
            } else {
                BiddingActivity.openActivity(mContext,biddingId)
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        if (msg.code == 0) {
            viewModel.getGoodsDetail(biddingId)
        } else if (msg.code == 2) {
            viewModel.goodDetailDto.value!!.product.isFavorites = !(msg.obj as Boolean)
            if (viewModel.goodDetailDto.value!!.product.isFavorites) {
                XToast.success(getString(R.string.already_success))
                llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
            } else {
                XToast.success(getString(R.string.cancel_collect))
                llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
            }
        } else if (msg.code == 3) {
            viewModel.goodDetailDto.value!!.isRemind = !(msg.obj as Boolean)
            if (viewModel.goodDetailDto.value!!.isRemind) {
                llStar.text = getString(R.string.already_remind)
                AlertDialog.Builder(this)
                    .setTitle(getString(R.string.setting_remind_success))
                    .setMessage(getString(R.string.remind_success_content))
                    .setCancelable(true)
                    .setPositiveButton(getString(R.string.i_got_it)) { _, _ ->
                    }.create().show()
            } else {
                llStar.text = getString(R.string.remind)
                XToast.success(getString(R.string.already_cancel_remind))
            }
        } else if (msg.code == 4) {
            GoodsDetailsActivity.openActivity(mContext, msg.arg1)
        }
    }

    override fun onResume() {
        super.onResume()
        my_banner.startAutoPlay()
    }

    override fun onPause() {
        super.onPause()
        my_banner.stopAutoPlay()
    }

    private fun initBanner() {
        my_banner.loadImage { _, model, view, _ ->
            ImageAdapter.setNomalImageUrl(
                view as ImageView,
                (model as BannerDto.SlideListBean).image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, goodId: Int, biddingId: Int) {
            mContext.startActivity(
                bundleOf(Pair("goodId", goodId),Pair("biddingId", biddingId)),
                BiddingCommodityActivity::class.java
            )
        }
    }
}
